/*
 *@author: YangJie
 *@date: 2021-04-16 16:12:10
 *@version:
 *@description:参数设置->设备参数设置->编码规则
 */
import React from 'react';
import { Tabs, Table, Input, Button, Form, notification,Modal } from 'antd';
import '@/assets/css/settings';
import { euqApplicationName } from '../../../config';
const { TabPane } = Tabs;

function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};
const columsTitle = [
	{
		key: 'codeRules',
		title: '编码规则',
		dataIndex: 'codeRules',
		width: '40%',
		editable: true
	},
	{
		key: 'textRules',
		title: '规则内容',
		width: '40%',
		dataIndex: 'textRules', 
		editable: true
	}
];
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
	<EditableContext.Provider value={form}>
		<tr {...props} />
	</EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);

//可修改的cell
class EditableCell extends React.Component {
	state = {
		editing: false
	};

	toggleEdit = () => {
		const editing = !this.state.editing;
		this.setState({ editing }, () => {
			if (editing) {
				this.input.focus();
			}
		});
	};

	save = e => {
		const { record, handleSave } = this.props;
		this.form.validateFields((error, values) => {
			if (error && error[e.currentTarget.id]) {
				return;
			}
			this.toggleEdit();
			handleSave({ ...record, ...values });
		});
	};

	renderCell = form => {
		this.form = form;
		const { children, dataIndex, record, title } = this.props;
		const { editing } = this.state;
		return editing ? (
			<Form.Item style={{ margin: 0 }}>
				{form.getFieldDecorator(dataIndex, {
					rules: [
						{
							required: true,
							message: `${title} 必须填写.`
						}
					],
					initialValue: record[dataIndex]
				})(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
			</Form.Item>
		) : (
			<div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={this.toggleEdit}>
				{children}
			</div>
		);
	};

	render() {
		const { editable, dataIndex, title, record, index, handleSave, children, ...restProps } = this.props;
		return <td {...restProps}>{editable ? <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer> : children}</td>;
	}
}

class EncodingRules extends React.Component {
	state = {
		loading: false, //加载中...
		loading_file: false,
		dataSource: [],
		datatestDetails: [],
		visible: false, //显示与隐藏
		btnDrawer: false,
		btnDrawer_file: false,
		modalData: '',//选中的数据
		handleType: 0,
		pagination: {
			pageSize: 10,
			current: 1
		},
		visible2: false,
		tabKey: '1',
		itemType: 1,
		chouyangType: '2',
		reportRepairNoDataSource: [],
		equipmentDataSource: [],
		repairDataSource: [],
		maintainDataSource: [],
	};
	componentDidMount() {
		this.fetch()
	}
	//初始化加载数据
	fetch = data => {
		this.setState({ loading: true })
		this.get(euqApplicationName + '/api/findCodeRulesPageList').then(res => {
			console.log(res.data.data)
			let data = res.data.data
			let reportRepairNoDataSource = []
			let equipmentDataSource = []
			let repairDataSource = []
			let maintainDataSource = []
			for (const item of data) {
				if (item.type === 1) {
					reportRepairNoDataSource.push(item)
					this.setState({ reportRepairNoDataSource })
				} else if (item.type === 2) {
					equipmentDataSource.push(item)
					this.setState({ equipmentDataSource })
				} else if (item.type === 3) {
					repairDataSource.push(item)
					this.setState({ repairDataSource })
				} else if (item.type === 4) {
					maintainDataSource.push(item)
					this.setState({ maintainDataSource })
				}
			}
			console.log(this.state)
			// this.setState({
			// 	loading: false,
			// 	dataSource: res.data.data,
			// 	total:res.data.total,
			// 	formValues:data
			// });
		})
	};

	handleDeleteconfirm = (record,type) => {
		const p = this
		Modal.confirm({
			title: '提示',
			content: '确认删除?',
			onOk() {
				p.handleDelete(record.id, type)
			},
			onCancel() {
				console.log('Cancel');
			},
			okText:"确认",
			 cancelText:"取消"
		  })
	}
	constructor(props) {
		super(props);
		this.reportRepairNoColumns = [
			...columsTitle,
			{
				title: '操作',
				dataIndex: 'action',
				render: (text, record) =>
					this.state.reportRepairNoDataSource.length >= 1 ? (<a onClick={() => this.handleDelete(record.id, 'REPORT')}>删除</a>) : null
			}
		];
		this.equipmentColumns = [
			...columsTitle
			// {
			// 	title: '操作',
			// 	dataIndex: 'action',
			// 	render: (text, record) =>
			// 		this.state.equipmentDataSource.length >= 1 ? (
			// 			<Popconfirm title="确认删除？" onConfirm={() => this.handleDelete(record.id, 'EQUIPMENT')}  okText="是" cancelText="否">
			// 				<a>删除</a>
			// 			</Popconfirm>
			// 		) : null
			// }
		];
		this.repairDataSourceColumns = [
			...columsTitle,
			{
				title: '操作',
				dataIndex: 'action',
				render: (text, record) =>
					this.state.repairDataSource.length >= 1 ? (<a onClick={() => this.handleDelete(record.id, 'REPAIR')}>删除</a>) : null
			}
		];
		this.maintainDataSourceColumns = [
			...columsTitle,
			{
				title: '操作',
				dataIndex: 'action',
				render: (text, record) =>
					this.state.maintainDataSource.length >= 1 ? (<a onClick={() => this.handleDelete(record.id, 'MAINTAIN')}>删除</a>) : null
			}
		];

		this.setState({
			reportRepairNoCount: this.state.reportRepairNoDataSource ? this.state.reportRepairNoDataSource.length : 0,
			equipmentCount: this.state.equipmentDataSource ? this.state.equipmentDataSource.length : 0,
			repairCount: this.state.repairDataSource ? this.state.repairDataSource.length : 0,
			maintainCount: this.state.maintainDataSource ? this.state.maintainDataSource.length : 0
		});
	}

	handleDelete = (key, type) => {
		const {reportRepairNoDataSource,equipmentDataSource,repairDataSource,maintainDataSource} = this.state
		const p = this
		Modal.confirm({
			title: '提示',
			content: '确认删除?',
			onOk() {
				// p.get(euqApplicationName + '/api/deleteRule?ids=' + key).then(res1 => {
				// 	openNotification('success', '删除成功！')
				// 	p.fetch()
				// })
				switch (type) {
					case 'REPORT': {
						p.setState({ reportRepairNoDataSource: reportRepairNoDataSource.filter(item => item.id !== key) });
						break;
					}
					case 'EQUIPMENT': {
						p.setState({ equipmentDataSource: equipmentDataSource.filter(item => item.id !== key) });
						break;
					}
					case 'REPAIR': {
						p.setState({ repairDataSource: repairDataSource.filter(item => item.id !== key) });
						break;
					}
					case 'MAINTAIN': {
						p.setState({ maintainDataSource: maintainDataSource.filter(item => item.id !== key) });
						break;
					}
					default: {
						break;
					}
				}
			},
			onCancel() {
				console.log('Cancel');
			},
			okText:"确认",
			cancelText:"取消"
		})
		
		// switch (type) {
		// 	case 'REPORT': {
		// 		// this.get(euqApplicationName + '/api/deleteRule?ids='+key).then(res1=>{
		// 		// 	this.fetch()
		// 		// })
		// 		this.setState({ reportRepairNoDataSource: reportRepairNoDataSource.filter(item => item.id !== key) });
		// 		break;
		// 	}
		// 	case 'EQUIPMENT': {
		// 		// this.get(euqApplicationName + '/api/deleteRule?ids='+key).then(res1=>{
		// 		// 	this.fetch()
		// 		// })
		// 		this.setState({ equipmentDataSource: equipmentDataSource.filter(item => item.id !== key) });
		// 		break;
		// 	}
		// 	case 'REPAIR': {
		// 		this.setState({ repairDataSource: repairDataSource.filter(item => item.id !== key) });
		// 		break;
		// 	}
		// 	case 'MAINTAIN': {
		// 		this.setState({ maintainDataSource: maintainDataSource.filter(item => item.id !== key) });
		// 		break;
		// 	}
		// 	default: {
		// 		break;
		// 	}
		// }
	};

	handleAdd = type => {
		const { reportRepairNoCount, reportRepairNoDataSource } = this.state;
		const { equipmentCount, equipmentDataSource } = this.state;
		const { repairCount, repairDataSource } = this.state;
		const { maintainCount, maintainDataSource } = this.state;
		const newData = {
			key: equipmentCount,
			codeRules: '单号规则',
			textRules: '规则内容'
		};
		switch (type) {
			case 'REPORT': {
				newData.type = 1;
				this.setState({
					reportRepairNoDataSource: [...reportRepairNoDataSource, newData],
					reportRepairNoCount: reportRepairNoCount + 1
				});
				break;
			}
			case 'EQUIPMENT': {
				newData.type = 2;
				this.setState({
					equipmentDataSource: [...equipmentDataSource, newData],
					equipmentCount: equipmentCount + 1
				});
				break;
			}
			case 'REPAIR': {
				newData.type = 3;
				this.setState({
					repairDataSource: [...repairDataSource, newData],
					repairCount: repairCount + 1
				});
				break;
			}
			case 'MAINTAIN': {
				newData.type = 4;
				this.setState({
					maintainDataSource: [...maintainDataSource, newData],
					maintainCount: maintainCount + 1
				});
				break;
			}
			default:
				break;
		}
	};

	//所有的都调用的是这一个save方法，后续需要调整，要么整合要么每个类型一个
	handleSave_reportRepairNoDataSource = row => {
		const newData = [...this.state.reportRepairNoDataSource];
		const index = newData.findIndex(item => row.id === item.id);
		const item = newData[index];
		newData.splice(index, 1, {
			...item,
			...row
		});
		this.setState({ reportRepairNoDataSource: newData });
	};
	handleSave_equipmentDataSource = row => {
		const newData = this.state.equipmentDataSource;
		const index = newData.findIndex(item => row.id === item.id);
		const item = newData[index];
		newData.splice(index, 1, {
			...item,
			...row
		});
		this.setState({ equipmentDataSource: newData });
	};
	handleSave_maintainDataSource = row => {
		const newData = [...this.state.maintainDataSource];
		const index = newData.findIndex(item => row.id === item.id);
		const item = newData[index];
		newData.splice(index, 1, {
			...item,
			...row
		});
		this.setState({ maintainDataSource: newData });
	};
	handleSave_repairDataSource = row => {
		const newData = [...this.state.repairDataSource];
		const index = newData.findIndex(item => row.id === item.id);
		const item = newData[index];
		newData.splice(index, 1, {
			...item,
			...row
		});
		this.setState({ repairDataSource: newData });
	};

	saves = () => {
		// console.log(this.state.reportRepairNoDataSource)
		// console.log(this.state.equipmentDataSource)
		// console.log(this.state.maintainDataSource)
		// console.log(this.state.repairDataSource)
		let data = []
		data.push.apply(data, this.state.reportRepairNoDataSource)
		data.push.apply(data, this.state.equipmentDataSource)
		data.push.apply(data, this.state.maintainDataSource)
		data.push.apply(data, this.state.repairDataSource)
		console.log(data)
		this.post(euqApplicationName + '/api/addCodeRulesList', { data }).then(res => {
			openNotification('success', '保存成功！')
			this.fetch()
		})
	}
	render() {
		const { reportRepairNoDataSource, equipmentDataSource, repairDataSource, maintainDataSource } = this.state;
		const components = {
			body: {
				row: EditableFormRow,
				cell: EditableCell
			}
		};
		const reportRepairNoDataSourceColumns = this.reportRepairNoColumns.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave_reportRepairNoDataSource
				})
			};
		});

		const equipmentDataSourceColumns = this.equipmentColumns.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave_equipmentDataSource
				})
			};
		});

		const repairDataSourceColumns = this.repairDataSourceColumns.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave_repairDataSource
				})
			};
		});

		const maintainDataSourceColumns = this.maintainDataSourceColumns.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave_maintainDataSource
				})
			};
		});

		return (
			<div className="shadow-radius">
				<Tabs>
					<TabPane tab="编码规则" key="1">
						<div className="content-title">设备编码规则</div>
						<Table components={components} rowClassName={() => 'editable-row'} bordered dataSource={equipmentDataSource} columns={equipmentDataSourceColumns} pagination={false} style={{ width: '50%' }} />
						{/* <Button icon="plus" onClick={() => this.handleAdd('REPORT')} type="primary">
							添加
						</Button> */}
						<div className="content-title">报修单号规则</div>
						<p>注：单号规则中可以只使用部分前缀，如只用日期+数字，或只用数字！</p>
						<p>日期前缀中yyyy为年，MM为月，dd为日，数字前缀中000为当日自增序号位数为3位</p>
						<Button icon="plus" onClick={() => this.handleAdd('REPORT')} type="primary">
							添加
						</Button>
						<Table components={components} rowClassName={() => 'editable-row'} bordered dataSource={reportRepairNoDataSource} columns={reportRepairNoDataSourceColumns} pagination={false} style={{ width: '50%' }} />
						<div className="content-title">维修单号规则</div>
						<Button icon="plus" onClick={() => this.handleAdd('REPAIR')} type="primary">
							添加
						</Button>
						<Table components={components} rowClassName={() => 'editable-row'} bordered dataSource={repairDataSource} columns={repairDataSourceColumns} pagination={false} style={{ width: '50%' }} />
						<div className="content-title">保养单号规则</div>
						<Button icon="plus" onClick={() => this.handleAdd('MAINTAIN')} type="primary">
							添加
						</Button>
						<Table components={components} rowClassName={() => 'editable-row'} bordered dataSource={maintainDataSource} columns={maintainDataSourceColumns} pagination={false} style={{ width: '50%' }} />
						<Button type="primary" style={{ margin: '1% 0 0 21%' }} onClick={() => { this.saves() }}>
							保存
						</Button>
					</TabPane>
				</Tabs>
			</div>
		);
	}
}

export default Form.create()(EncodingRules);
